#!/bin/bash

echo "=========================================="
echo "初始化LocalStack AWS资源..."
echo "=========================================="

# 等待LocalStack完全启动
sleep 5

# 设置端点
ENDPOINT="http://localhost:4566"

echo "1. 创建Kinesis Data Stream..."
awslocal kinesis create-stream \
  --stream-name click-events-stream \
  --shard-count 1 \
  --region us-east-1 2>/dev/null || echo "   Stream 已存在，跳过创建"

echo "2. Stream 已创建（LocalStack 无需等待激活）"

echo "3. 打包Lambda函数..."
cd /tmp
mkdir -p lambda-package
cp -r /etc/localstack/init/ready.d/../../../lambda/* lambda-package/ 2>/dev/null || echo "Lambda代码将后续部署"

echo "4. 创建Lambda IAM Role..."
awslocal iam create-role \
  --role-name LambdaExecutionRole \
  --assume-role-policy-document '{
    "Version": "2012-10-17",
    "Statement": [{
      "Effect": "Allow",
      "Principal": {"Service": "lambda.amazonaws.com"},
      "Action": "sts:AssumeRole"
    }]
  }' \
  --region us-east-1 || true

echo "5. 附加Lambda策略..."
awslocal iam attach-role-policy \
  --role-name LambdaExecutionRole \
  --policy-arn arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole \
  --region us-east-1 || true

awslocal iam attach-role-policy \
  --role-name LambdaExecutionRole \
  --policy-arn arn:aws:iam::aws:policy/AmazonKinesisFullAccess \
  --region us-east-1 || true

echo "6. Lambda函数将由部署脚本创建..."
echo "   使用: ./scripts/deploy-lambda.sh"

echo "7. API Gateway将由部署脚本创建..."
echo "    使用: ./scripts/deploy-lambda.sh"

echo "=========================================="
echo "LocalStack初始化完成！"
echo "=========================================="
echo ""
echo "资源列表:"
echo "- Kinesis Stream: click-events-stream"
echo ""
echo "下一步: 运行 ./scripts/deploy-lambda.sh 部署Lambda和API Gateway"
echo "=========================================="

